package manager

import (
	"net/http"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/oplogd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/debug"

	"github.com/gin-gonic/gin"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/ginsess"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/columns"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/feedback"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/groups"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/infos"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/ints"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/orgs"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/manager/reviews"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/oplog"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd/ginhook"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd/repo/mgorepo"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"
)

// Init 初始化管理api
func Init(s ginsrv.Server, sopt ginsess.Option) {
	s.RegStartHook(func(e *gin.Engine) {
		route := e.Group("/cms", ginsess.Sessions(sopt))
		route.Use(ginhook.DDDContext(func(c *gin.Context) string {

			uid, ok := getUID(ginsess.FromContext(c))
			if !ok {
				if debug.IsDev() {
					uid = "000000"

				}
			}
			oplog.WrapModules(c, func(ol *oplogd.OpLogEntity) {
				ol.Module = "cms"
				ol.UID = uid
			})
			return uid
		}))
		route.Use(mgorepo.MgoContext(s.Domain()))

		cored := s.Domain().(core.CmsDomain)
		route.Use(oplog.Oplog(cored.OpLog()))
		// ulogin := createUlogin(cored)
		// route.POST("login", oplog.OplogRoute("login", "管理端登录", ulogin.login))
		// route.GET("logout", oplog.OplogRoute("logout", "管理端登出", ulogin.logout))

		route = route.Group("v1", func(c *gin.Context) {

			if uid, ok := getUID(ginsess.FromContext(c)); !ok {
				if debug.IsDev() {
					log.Debug("开发模拟用户id：000000")
					s := ginsess.FromContext(c)
					setUID(s, "000000")
					return
				}
				c.JSON(http.StatusUnauthorized, gin.H{"status": 1, "error": "未认证不能操作"})
				c.Abort()
			} else {
				c.Set("__uid__", uid)
				log.WrapUIDForContext(c, uid)
			}
		})

		// startup := createStartupCtrl()
		// route.GET("startup/load", startup.load)
		columns.Init(route, cored)
		infos.Init(route.Group("infos"), cored)
		feedback.Init(route.Group("feedback"), cored)
		reviews.Init(route.Group("reviews"), cored)
		groups.Init(route, cored)
		orgs.Init(route.Group("orgs"), cored)
		ints.Init(route.Group("ints"), cored)
		// 信息相关

	})
}
